<template>
  <div class="tabs_con">
    <div>
      <px-tabs v-model="tabsName" type="card" @tab-change="changeTabsFn">
        <px-tab-pane label="单指标分析" name="one" />
        <px-tab-pane label="多指标分析" name="many" />
      </px-tabs>
    </div>
    <div class="con_com">
      <div class="select_group">
        <px-radio-group v-if="tabsName === 'one'" v-model="targetRadio">
          <px-radio v-for="item in keyTypeList" :key="item.id" :label="item.type" border>{{ item.itemName }}</px-radio>
        </px-radio-group>
        <px-checkbox-group v-if="tabsName === 'many'" v-model="targetList">
          <px-checkbox v-for="item in keyTypeList" :key="item.id" :label="item.type" border>{{ item.itemName }}</px-checkbox>
        </px-checkbox-group>
        <px-checkbox-group v-model="checkAreaList" class="check_group" @change="checkListChange">
          <px-checkbox v-for="item in areaData" :key="item.code" :label="item.name">{{ item.name }}</px-checkbox>
        </px-checkbox-group>
      </div>
      <px-form ref="querySpcRef" class="custom-form-ui inspection-form" :model="Detail" :inline="true">
        <px-form-item v-show="false" label="时间日期" style="width: 430px">
          <px-date-picker
            v-model="dateRangeSpc"
            disabled
            :clearable="false"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :defaultTime="defaultTime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </px-form-item>
        <px-form-item label="周期" prop="testCompany" style="width: 200px">
          <px-select v-model="Detail.testCompany" filterable placeholder="请选择周期" @change="handleQuerySpc">
            <px-option v-for="item in testCompanyList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <!-- <div class="spc_target">
          <px-radio-group v-model="spcTarget">
            <px-radio-button label="ALARM" />
            <px-radio-button label="OOS" />
            <px-radio-button label="OOC" />
            <px-radio-button label="OOW" />
            <px-radio-button label="RULE-1" />
            <px-radio-button label="RULE-2" />
            <px-radio-button label="ALL" />
          </px-radio-group>
        </div> -->
        <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
        <px-button icon="" @click="resetQuery">重置</px-button>
      </px-form>
      <div class="chart_con">
        <div v-if="tabsName === 'one'" class="chart_item" :style="{ width: checkAreaList.length > 4 ? '100%' : '49%' }">
          <lineChart ref="heatMapRef" :key="midKey" :options="heatMapOptions" :width="600" :height="480" />
          <!-- <div ref="heatMapRef" style="min-width: 600px; height: 480px; border: 1px solid #dcdcdc" /> -->
        </div>
        <div class="chart_item" :style="{ width: checkAreaList.length > 4 || tabsName === 'many' ? '100%' : '49%' }">
          <lineChart ref="areaChartRef" :key="midKey + 10" :options="linesOptions" :width="600" :height="480" />
        </div>
      </div>
      <div class="btn_table">
        <barTitle title="明细" />
        <px-table v-loading="loading" :header-cell-style="{ background: '#e7eefb', color: '#000' }" border :data="tableData" show-overflow-tooltip>
          <!-- <px-table-column width="100" label="厂区" align="center" prop="id" /> -->
          <px-table-column label="时间" align="center" prop="alarmTime" width="160" />
          <px-table-column label="组" align="center" prop="factoryId" />
          <px-table-column label="名称" align="center" prop="point" />
          <px-table-column label="报警信息" align="center" prop="alarmContent" width="100" />
          <px-table-column label="级别" align="center" prop="alarmLevel" />
          <px-table-column label="当前值" align="center" prop="realityValue" />
          <px-table-column label="报警限" align="center" prop="settingValue" />
          <px-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
            <template #default="scope">
              <px-tooltip content="批注" placement="top">
                <px-button v-has="'FFU_LEDGER_EDIT'" link type="primary" icon="Edit" @click="addAlarmRemake(scope.row)" />
              </px-tooltip>
              <px-tooltip content="历史批注" placement="top">
                <px-button v-has="'FFU_LEDGER_COPY'" link type="primary" icon="Clock" @click="getcontentList(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>

        <pagination
          v-show="tableDataAll && tableDataAll.length > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="tableDataAll.length"
          @pagination="queryAlarmTable"
        />
      </div>
      <div v-if="tabsName === 'one'" class="btn_box">
        <barTitle title="Q部门 VS online检测" />
        <div class="btn_chart">
          <div class="chart_item">
            <!-- <lineChart ref="barChartsRef" :key="echartsKey" :labelLayoutFn="labelLayoutBarFn" :width="600" :height="480" /> -->
            <div v-show="barChartsRef" ref="barChartsRef" style="min-width: 600px; height: 480px; border: 1px solid #dcdcdc" />
            <div v-show="!barChartsRef" class="echarts-empty">
              <px-empty :image-size="100" />
            </div>
          </div>
          <div class="chart_item">
            <!-- <lineChart ref="spcChartsRef" :labelLayoutFn="labelLayoutLineFn" :width="600" :height="480" /> -->
            <spcCharts ref="spcChartsDom" :key="midKey" :width="600" :height="480" :optionData="spcOptions" color="#3B82F6" />
          </div>
        </div>
      </div>
    </div>
    <px-dialog v-model="contentVisible" title="批注历史" width="956" align-center>
      <px-table v-loading="hishoryLoading" class="digtable1" :data="contentList" height="250" show-overflow-tooltip border>
        <px-table-column label="时间" prop="createTime">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </px-table-column>
        <px-table-column label="批注人" prop="creator">
          <template #default="scope">
            <span>{{ scope.row.creator }}</span>
          </template>
        </px-table-column>
        <px-table-column label="内容" prop="content">
          <template #default="scope">
            <span>{{ scope.row.content }}</span>
          </template>
        </px-table-column>

        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>
      <pagination
        v-show="total2 > 0"
        v-model:page="queryHistoryParams.pageNum"
        v-model:limit="queryHistoryParams.pageSize"
        style="margin-bottom: -10px"
        :total="total2"
        @pagination="queryAlarmHistory"
      />
      <!-- <template #footer>
        <span class="dialog-footer">
          <px-button @click="progressVisible = false">取消</px-button>
          <px-button type="primary" @click="addRukudetails()"> 确认 </px-button>
        </span>
      </template> -->
    </px-dialog>
    <px-dialog v-model="contentTextVisible" title="批注" width="677" align-center>
      <px-row class="contentrow">
        <px-col :span="24">
          <px-input v-model="alarmRemake" style="margin-top: 16px" :rows="2" type="textarea" placeholder="请输入" />
        </px-col>
      </px-row>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="contentTextVisible = false">取消</px-button>
          <px-button type="primary" @click="addcontent()"> 保存 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, markRaw, computed, onMounted, onUnmounted, toRefs, reactive, getCurrentInstance } from "vue";
import { PxMessage } from "px-ui";
import spcCharts from "@/views/machine/components/spcCharts/index.vue";
import { spcquerySpcAnalysis } from "@/api/spc";
import lineChart from "@/views/machine/operation/environmentTestManage/components/lineChart/index.vue";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import * as echarts from "echarts";
import barTitle from "@/views/machine/components/barTitle/index.vue";
import {
  queryWeatherData,
  getFabZone,
  getReadersInZone,
  getReadersInZoneByType,
  getPointNewValue,
  getPointsCurve,
  getBarChartsData,
  addRemake,
  remakeHistory,
  queryChildByTypeCodeAndItemValue,
  queryAreaWornings
} from "@/api/machineClass";

const { proxy }: any = getCurrentInstance();

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];

const props = defineProps({
  activeName: {
    type: String,
    default: () => ""
  }
});

const heatMapRef = ref(null);
const areaChartRef = ref(null);
const barChartsRef = ref(null);
const spcChartsRef = ref(null);
const total = ref(0);
const searchId = ref("");
const tabsName = ref("one");
const targetRadio = ref("");
const spcTarget = ref("ALL");
const loading = ref(false);
const contentVisible = ref(false);
const contentTextVisible = ref(false);
const chosedAlarm = ref("");
const viewAlarm = ref("");
const alarmRemake = ref("");
const total2 = ref(0);
const hishoryLoading = ref(false);

const echartsKey = ref<string>(Math.random().toString(36).slice(2, 10));
const midKey = ref(Date.now());

const testCompanyList = ref<any>([
  {
    value: "12 minutes",
    key: 240,
    label: "近4小时"
  },
  {
    value: "3 minutes",
    key: 60,
    label: "近1小时"
  },
  {
    value: "60 seconds",
    key: 30,
    label: "近30分钟"
  },
  {
    value: "20 seconds",
    key: 10,
    label: "近10分钟"
  },
  {
    value: "1 hours",
    key: 1440,
    label: "近1天"
  },
  {
    value: "7 hours",
    key: 10080,
    label: "近7天"
  },
  {
    value: "1 days",
    key: 43200,
    label: "近30天"
  }
]);

const state = reactive<any>({
  checkAreaList: [],
  contentList: [],
  heatMapOptions: {},
  linesOptions: {},
  spcOptions: {},
  dateRangeSpc: [],
  tableData: [],
  tableDataAll: [],
  areaData: [],
  keyTypeList: [],
  pointsList: [],
  targetList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  queryHistoryParams: {
    pageNum: 1,
    pageSize: 10
  },
  Detail: {
    testCompany: "12 minutes"
  }
});

const {
  checkAreaList,
  dateRangeSpc,
  queryParams,
  queryHistoryParams,
  pointsList,
  tableData,
  areaData,
  contentList,
  spcOptions,
  targetList,
  heatMapOptions,
  linesOptions,
  Detail,
  tableDataAll,
  keyTypeList
} = toRefs(state);

const spcChartsDom = ref(null);

const getParams = computed(() => {
  const obj = {
    zones: [],
    types: [],
    factory: {
      id: 1,
      parentCode: "",
      code: "",
      name: "",
      type: "",
      path: "",
      // facCode: "FAC_83abf9",
      principalId: 1,
      principalName: "",
      className: "MACHINE",
      children: [
        {
          id: 1,
          parentCode: "",
          code: "",
          name: "",
          type: "",
          path: "",
          // facCode: "",
          principalId: 1,
          principalName: "",
          className: ""
        }
      ]
    },
    requestId: ""
  };
  if (tabsName.value === "one") {
    obj.types = [targetRadio.value];
    obj.zones = [...checkAreaList.value];
    return obj;
  } else {
    obj.types = [...targetList.value];
    obj.zones = [...checkAreaList.value];
    return obj;
  }
});

// 循环获取点位列表，再循环点位列表获取热力图数据
const getPointsList = async (param: any, arr) => {
  let list = [];
  const pointObj: any = await getReadersInZoneByType(param);
  arr.push(...pointObj);
  pointsList.value = arr;
  // arr = ["AMC_F_LITHO", "VT_AMC_PPM_EPI_F", "VT_AMC_PPM_EPI_CL", "VT_AMC_PPM_EPI_NO3"];
  if (arr.length) {
    for (let i = 0; i < arr.length; i++) {
      const str1 = arr[i];
      const params = {
        panelCode: "cr_heatmap",
        criteria: {
          timespan: Detail.value.testCompany,
          startTime: dateRangeSpc.value[0],
          endTime: dateRangeSpc.value[1],
          // startTime: "2024-09-13 11:40:00",
          // endTime: "2024-09-15 12:13:24",
          points: [str1]
        }
      };
      queryHeatMap(params, list, param);
    }
  }
  // console.log(arr, "点位列表");
};

// 循环调用接口获取点位列表
const getHotPointes = () => {
  let arr = [];
  // console.log(getParams.value, "getParams.value,区域/指标");
  for (let i = 0; i < getParams.value.zones.length; i++) {
    for (let j = 0; j < getParams.value.types.length; j++) {
      const str1 = getParams.value.zones[i];
      const str2 = getParams.value.types[j];
      const obj = {
        ...getParams.value
      };
      obj.zones = [str1];
      obj.types = [str2];
      getPointsList(obj, arr);
    }
  }
  // pointsList.value.forEach(el => {
  //   queryHeatMap(el);
  // });
};

// 热力图
const queryHeatMap = async (param, list, obj) => {
  // const param = {
  //   panelCode: "cr_heatmap",
  //   criterial: {
  //     timespan: Detail.value.testCompany,
  //     startTime: dateRangeSpc.value[0],
  //     endTime: dateRangeSpc.value[1],
  //     points: ["AMC_F_LITHO"]
  //   }
  // };
  const res: any = await getPointNewValue(param);
  list.push(res);
  const hours = list && list.length ? list[0].rows.map(item => item.timespan) : [];
  // console.log(hours, "横坐标");
  const seriesHeatMap = list.map((item, index) => {
    return {
      name: checkAreaList.value[index] || (item.rows && item.rows[0].point.split("_")[item.rows[0].point.split("_").length - 1]),
      type: "heatmap",
      data: item.rows
        .map((el, ind) => {
          return [index, ind, el.last_value];
        })
        .map(function (e) {
          return [e[1], e[0], e[2] || "-"];
        }),
      label: {
        show: true
      },
      itemStyle: {
        normal: {
          // width: 30,// 设置格子宽度
          height: 30 // 设置格子高度
        }
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: "rgba(0, 0, 0, 0.5)"
        }
      }
    };
  });
  const seriesLine = list.map((item, index) => {
    return {
      name: checkAreaList.value[index] || (item.rows && item.rows[0].point.split("_")[item.rows[0].point.split("_").length - 1]),
      type: "line",
      yAxisIndex: index,
      emphasis: {
        focus: "series",
        blurScope: "coordinateSystem"
      },
      data: item.rows.map(e => Number(e.last_value))
    };
  });
  const yAxisData = list.map((item, index) => {
    return {
      type: "value",
      name: `℃`,
      alignTicks: true,
      offset: (0 + index) * 50,
      axisLine: {
        lineStyle: {
          width: 2
        }
      }
    };
  });
  // prettier-ignore
  // const days = areaData.value.map((item: any) => item.name);
  // const yData = checkAreaList.value;
  const yData = seriesHeatMap.map(item => item.name);
  // console.log(seriesHeatMap, yData, hours, "热力图数据-y轴-X轴");
  // console.log(seriesLine, yAxisData, hours, "折线图数据-y轴-X轴");
  // prettier-ignore
  const data = [[0, 0, 5], [0, 1, 1], [0, 2, 0], [0, 3, 0], [0, 4, 0], [0, 5, 0], [0, 6, 0], [0, 7, 0], [0, 8, 0], [0, 9, 0], [0, 10, 0], [0, 11, 2], [0, 12, 4], [0, 13, 1], [0, 14, 1], [0, 15, 3], [0, 16, 4], [0, 17, 6], [0, 18, 4], [0, 19, 4], [0, 20, 3], [0, 21, 3], [0, 22, 2], [0, 23, 5], [0, 24, 7], [0, 25, 0], [0, 26, 0], [0, 27, 0], [0, 28, 0], [0, 29, 0], [0, 30, 0], [0, 31, 0]]
    .map(function (item) {
      return [item[1], item[0], item[2] || '-'];
    });
  // console.log(data, "热力图data");
  const options: UtilsEChartsOption = {
    title: {
      text: "Temperature Distribution Across FAB Areas Over Time",
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      position: "top"
    },
    grid: {
      height: "68%",
      left: "8%",
      top: "10%",
      right: "24px"
    },
    xAxis: {
      type: "category",
      data: hours || [],
      splitArea: {
        show: true
      }
    },
    yAxis: {
      type: "category",
      data: yData || [],
      splitArea: {
        show: true
      }
    },
    visualMap: {
      // pieces: [
      //   { min: 0, max: 5, color: "blue" },
      //   { min: 6, max: 10, color: "red" }
      // ],
      min: 0,
      max: 15,
      calculable: true,
      orient: "horizontal",
      left: "center",
      bottom: "2%"
    },
    series: seriesHeatMap || []
  };
  const lineOptions: UtilsEChartsOption = {
    title: {
      text: "Temperature Trends Across FAB Areas Over Time",
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      // data: props.areaList.map((item: any) => item.name),
      data: seriesLine.map(item => item.name) || [],
      orient: "horizontal",
      bottom: "0"
    },
    grid: {
      left: "5%",
      top: "15%",
      right: `${yAxisData.length * 30}`,
      bottom: "24PX",
      containLabel: true
    },
    xAxis: {
      // type: "category",
      data: hours || []
    },
    yAxis: yAxisData || [],
    series: seriesLine || []
  };
  heatMapOptions.value = options;
  linesOptions.value = lineOptions;
  midKey.value = Date.now();
};

const checkListChange = async (val: any) => {
  // console.log(val);
  const heatMapDom = await heatMapRef.value.getEcharts();
  const lineChartDom = await areaChartRef.value.getEcharts();
  if (val.length === 5) {
    // console.log(heatMapDom, lineChartDom, "3333333");
    heatMapDom.resize();
    lineChartDom.resize();
  } else if (val.length === 4) {
    heatMapDom.resize();
    lineChartDom.resize();
    // console.log(heatMapDom, lineChartDom, "3333333");
  } else {
    return;
  }
};

const changeTabsFn = async (val: any) => {
  const lineChartDom = await areaChartRef.value.getEcharts();
  lineChartDom.resize();
};

const queryAlarmTable = (val: any) => {
  console.log(val);
  queryParams.value.pageNum = val.page;
  queryParams.value.pageSize = val.limit;
  const startIndex = (val.page - 1) * val.limit;
  const endIndex = startIndex + val.limit;
  tableData.value = tableDataAll.value.slice(startIndex, endIndex);
};

const mins = computed(() => {
  return testCompanyList.value.filter(item => item.value === Detail.value.testCompany)[0].key;
});

// 查询
const handleQuery = async () => {
  console.log(checkAreaList.value, "已选区域列表");
  getHotPointes();
  initSpc();
};

/** 重置按钮操作 */
function resetQuery() {
  const startTime = proxy.parseTime(new Date().getTime() - 240 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}");
  const endTime = proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}");
  dateRangeSpc.value = [startTime, endTime];
  Detail.value.testCompany = "12 minutes";
  handleQuery();
}

const handleQuerySpc = (val: string) => {
  const num: number = testCompanyList.value.filter(item => item.value === val)[0].key;
  if (val) {
    dateRangeSpc.value = initDate(num);
  }
};

// 获取区域列表
const queryAreaList = async (id: string) => {
  const data: any = await getFabZone();
  // data.forEach((item: any) => {
  //   getWorningNum(item.code);
  // });
  const arr = data.filter(item => item.code !== "ROOM_7b09b7");
  areaData.value = arr;
  checkAreaList.value = [areaData.value[0].name || ""];
};

// 根据区域获取报警信息
const getWorningNum = async (id: string, arr) => {
  const params = {
    // areaId: id, // id 暂时写死联调
    // roomId: "ROOM_b20032", // id 暂时写死联调
    pageNum: 1,
    pageSize: 999
  };
  params[`${id.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] = id.indexOf("ROOM") === -1 ? [id] : id;
  const res: any = await queryAreaWornings(params);
  arr.push(...res.data);
  const dataList = Array.from(new Set(arr));
  tableData.value = dataList.slice(queryParams.value.pageNum - 1, queryParams.value.pageSize);
  tableDataAll.value = dataList || [];
  total.value = dataList.length;
};

// 查询报警明细
const queryTable = async () => {
  let arr = [];
  areaData.value.forEach((item: any) => {
    getWorningNum(item.code, arr);
  });
};

const addAlarmRemake = (row: any) => {
  chosedAlarm.value = "alarm_" + row.alarmId;
  alarmRemake.value = "";
  contentTextVisible.value = true;
};

const addcontent = () => {
  addRemake({
    businessKey: chosedAlarm.value,
    content: alarmRemake.value
  }).then(res => {
    PxMessage({
      message: "批注成功",
      type: "success"
    });
    contentTextVisible.value = false;
  });
};

const getcontentList = row => {
  viewAlarm.value = row ? "alarm_" + row.alarmId : "";
  contentVisible.value = true;
  queryAlarmHistory();
};

const queryAlarmHistory = async () => {
  hishoryLoading.value = true;
  const res: any = await remakeHistory({
    businessKey: viewAlarm.value,
    ...queryHistoryParams.value
  });
  contentList.value = res?.data || [];
  total2.value = res?.total || 0;
  hishoryLoading.value = false;
};

// 日期转化
const initDate = (val: number) => {
  const now = new Date();
  const utcTime = now.toISOString();
  const beijingTime = new Date(utcTime).getTime() + 8 * 60 * 60 * 1000;
  const start = beijingTime - val * 60 * 1000;
  const startTime = new Date(start).toISOString().slice(0, 19).replace("T", " ");
  const endTime = new Date(beijingTime).toISOString().slice(0, 19).replace("T", " ");
  return [startTime, endTime];
};

let chartsInstance = null;

const getOnePoint = async (array1, array2) => {
  const obj = {
    zones: array1,
    types: array2,
    factory: {
      id: 1,
      parentCode: "",
      code: "",
      name: "",
      type: "",
      path: "",
      // facCode: "FAC_83abf9",
      principalId: 1,
      principalName: "",
      className: "MACHINE",
      children: [
        {
          id: 1,
          parentCode: "",
          code: "",
          name: "",
          type: "",
          path: "",
          // facCode: "",
          principalId: 1,
          principalName: "",
          className: ""
        }
      ]
    },
    requestId: ""
  };
  const pointObj: any = await getReadersInZoneByType(obj);
  const params = {
    pointList: [...pointObj],
    timePeriod: "hour",
    startTime: dateRangeSpc.value[0],
    endTime: dateRangeSpc.value[1]
  };
  const res: any = await spcquerySpcAnalysis(params);
  const spcList =
    res.length &&
    res.map((item: any) => {
      item.startTime = proxy.parseTime(new Date().getTime() - 24 * 60 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}");
      item.endTime = proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}");
      item.pointValues = item.pointValues ? item.pointValues : []; // null时判断，有数据可放开
      return {
        ...item
      };
    });
  spcOptions.value = spcList[0] || {};
  midKey.value = Date.now();
};

const initSpc = async () => {
  chartsInstance = markRaw(echarts.init(barChartsRef.value));
  const title = "AWC检测结果与在线监测数据对照";
  const param = {
    // facCode: "FAC_83abf9",
    className: "MACHINE",
    zones: checkAreaList.value, // checkAreaList.value
    sampleDate: proxy.parseTime(new Date().getTime() - 12 * 60 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}"),
    sampleCategory: "AMC",
    sampleSpec: targetRadio.value,
    requestId: ""
  };
  const res: any = await getBarChartsData(param);
  let arr = [["product", "Q部门", "online检测"]];
  res.forEach(item => {
    arr.push([item.sampleLocation, Number(item.sampleValueQ), Number(item.sampleValueR)]);
  });
  let legendData = res.map(item => item.sampleLocation);
  const data = { arr, legendData };
  const options: UtilsEChartsOption = {
    color: ["#4786FF", "#14C7C7"],
    title: {
      text: title,
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true,
      axisPointer: {
        type: "shadow"
      }
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      // data: props.areaList.map((item: any) => item.name),
      // data: data.legendData,
      orient: "horizontal",
      bottom: "0"
    },
    grid: {
      left: "24px",
      top: "15%",
      right: "24px",
      bottom: "5%",
      containLabel: true
    },
    dataset: {
      source: data.arr
    },
    xAxis: {
      type: "category"
      // data: ["12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: [
      {
        type: "value",
        // name: `单位`,
        alignTicks: true,
        axisLine: {
          lineStyle: {
            width: 2
          }
        }
      }
    ],
    series: [
      {
        type: "bar",
        barWidth: 16,
        itemStyle: {
          color: "#4786FF"
        },
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        }
      },
      {
        type: "bar",
        barWidth: 16,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#14C7C7"
        }
      }
    ]
  };
  if (barChartsRef.value && chartsInstance) {
    chartsInstance.setOption(options);
    const arr1 = [res[0].sampleLocation];
    const arr2 = [res[0].sampleSpec];
    getOnePoint(arr1, arr2); // 默认展示第一个区域的spc
    chartsInstance.on("click", params => {
      console.log(params, "9999999999999999");
      const spc_zone = res.filter(item => item.sampleLocation === params.name)[0].sampleLocation;
      const spc_job = res.filter(item => item.sampleLocation === params.name)[0].sampleSpec;
      console.log(res, spc_job);
      const zones = [spc_zone];
      const types = [spc_job];
      getOnePoint(zones, types);
    });
    window.addEventListener("resize", handelResize);
  }
};

const handelResize = () => {
  if (chartsInstance) {
    chartsInstance.resize();
  }
};

// window.addEventListener("resize", handelResize);

// 点位曲线
const labelLayoutLineFn = async (ec: any) => {
  const title = "SPC Chart for CL over 24 Hours";
  const param = {};
  const data = {};
  return labelLayoutFnLine(ec, data, title);
};

const labelLayoutFnLine = (ec: any, data: any, title: string) => {
  const { getWidth } = ec;
  // labelLine长度
  const labelLayout = function (params) {
    const isLeft = params.labelRect.x < getWidth() / 2;
    const points = params.labelLinePoints;
    points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
    return { labelLinePoints: points };
  };
  const options: UtilsEChartsOption = {
    title: {
      text: title,
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      // data: props.areaList.map((item: any) => item.name),
      data: ["WET", "ADF"],
      orient: "horizontal",
      bottom: "0"
    },
    grid: {
      left: "24px",
      top: "15%",
      right: "24px",
      bottom: "5%",
      containLabel: true
    },
    xAxis: {
      // type: "category",
      data: ["12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: [
      {
        type: "value",
        name: `单位`,
        alignTicks: true,
        axisLine: {
          lineStyle: {
            width: 2
          }
        }
      }
    ],
    series: [
      {
        name: "WET",
        type: "line",
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#4786FF"
        },
        data: [111, 2, 4, 123, 456]
      },
      {
        name: "ADF",
        type: "line",
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#FFB266"
        },
        data: [21, 62, 24, 383, 126]
      }
    ]
  };
  return options;
};

onMounted(async () => {
  dateRangeSpc.value = initDate(mins.value);
  // 通过厂区字典查询区域
  const codes: any = await queryChildByTypeCodeAndItemValue({
    value: "CR_ALL_CODES",
    typeCode: "MCTS"
  });
  // 查询指标列表
  const keysList: any = await queryChildByTypeCodeAndItemValue({
    value: "CIT01", // AMC :CIT01  温湿度：CIT04  particle:CIT03
    typeCode: "MCTS"
  });
  keyTypeList.value = keysList.map(item => {
    return {
      type: JSON.parse(item.itemDesc).attr,
      ...item
    };
  });
  targetRadio.value = keyTypeList.value[0].type;
  const id = JSON.parse(codes.filter(item => item.itemValue === "CR_POSITION_CODE")[0].itemDesc)[0].facCode; // 暂时写死一期厂区
  await queryAreaList(id);
  queryTable();
  getHotPointes();
  initSpc();
});
</script>

<style lang="scss" scoped>
.tabs_con {
  margin-top: 16px;
  background-color: #f0f2f5;

  :deep(.px-tabs__header) {
    border: none;
  }

  :deep(.px-tabs__nav) {
    margin: 0;
    border: none;
  }

  :deep(.px-tabs__item) {
    width: 118px;
    padding: 0 !important;
    text-align: center;
    border-radius: 4px 4px 0 0 !important;
  }

  :deep(.is-active) {
    background-color: white;
  }

  .con_com {
    width: 100%;
    min-width: 1300px;
    padding: 16px 24px;
    background-color: white;
    border-radius: 0 0 4px 4px;

    .select_group {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      width: 100%;

      .check_group {
        padding-left: 8px;
        border-left: 1px solid #ccc;
      }

      :deep(.px-checkbox) {
        margin-right: 8px;
      }
    }

    .chart_con {
      display: flex;
      flex-flow: row wrap;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      min-width: 1300px;
      margin-top: 16px;

      .chart_item {
        width: 49%;
        height: 480px;
        margin-bottom: 20px;
        border-radius: 4px;
      }
    }

    .btn_box {
      margin-top: 16px;

      .btn_chart {
        display: flex;
        flex-flow: row wrap;
        align-items: center;
        justify-content: space-between;
        min-width: 1300px;
        margin-top: 8px;

        .chart_item {
          width: 49%;
          height: 480px;
          margin-bottom: 20px;
          border-radius: 4px;

          .echarts-empty {
            display: flex;
            justify-content: center;
            min-width: 600px;
            height: 480px;
            margin: auto;
            border: 1px solid #dcdcdc;
          }
        }
      }
    }

    :deep(.px-radio) {
      margin-right: 8px;
    }

    .custom-form-ui {
      display: flex;
      align-items: center;
      margin-top: 8px;

      .spc_target {
        min-width: 495px;
        margin-right: 16px;
      }

      .px-form-item {
        margin-bottom: 0;
      }
    }
  }
}
</style>
